package net.notelife.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

public class JpgHandler implements HttpHandler {
	private String path;
	private String prefix;
	private int start;
	public JpgHandler(String dir,String prefix,int start) {
		this.path = dir;
		this.prefix = prefix;
		this.start = start;
	}

	@Override
	public void handle(HttpExchange exchange) throws IOException {
		try
		{
			String method = exchange.getRequestMethod();
			if("get".equalsIgnoreCase(method))
			{
				doGet(exchange);
			}
			else if("post".equalsIgnoreCase(method))
			{
				doPost(exchange);
			}
		}
		catch(Exception e)
		{
			System.out.println(e.toString());
		}

	}
	public void doPost(HttpExchange exchange) 
	{
		
	}
	public void doGet(HttpExchange exchange) 
	{
		File file = null;
		FileInputStream inputstream = null;
		byte[] bytes = new byte[1024];
		try
		{
			Headers headers = exchange.getRequestHeaders();
			for(String key:headers.keySet())
			{
				System.out.printf("%s:%s\n",key,headers.get(key));
			}
			String url = null;
			String[] paras = null;
			if(exchange.getRequestURI().toString().indexOf("?")>1)
			{
				paras = exchange.getRequestURI().toString().split("?")[1].split("&");
			}
			else
			{
				url = exchange.getRequestURI().toString();
			}
			String uri = path+File.separator + prefix + url.substring(start);
			file = new File(uri);
			inputstream = new FileInputStream(file);
			System.out.printf("path:%s\n",uri);
			InputStream in = null;
			in = exchange.getRequestBody();
			in.close();
			Headers resHeaders = exchange.getResponseHeaders();
			
			OutputStream out = null;
			out = exchange.getResponseBody();
			int rCode = 200;
			long responseLength = file.length();
			exchange.sendResponseHeaders(rCode,responseLength);
			int lenght = inputstream.read(bytes);
			while(lenght!=-1)
			{
				out.write(bytes,0,lenght);
				out.flush();
				lenght = inputstream.read(bytes);
			}
			inputstream.close();
			out.close();
		}
		catch(Exception e)
		{
			System.out.println(e.toString());
		}
	}

}
